<template>
  <div>
    <h1>{{ tit }}</h1>
    <table>
      <tr>
        <td>姓名</td>
        <td>手机号</td>
        <td>年龄</td>
        <td>
          <select v-model="sortAge">
            <option value="default">默认排序</option>
            <option value="asc">按年龄升序</option>
            <option value="desc">按年龄降序</option>
          </select>
        </td>
      </tr>
      <tr v-for="item in stuData" :key="item.id">
        <td>{{ item.name }}</td>
        <td>{{ item.contactNum }}</td>
        <td>{{ item.age }}</td>
        <td><button @click="del(item.id)">删除</button></td>
      </tr>
    </table>
  </div>
</template>

<script>
import { computed, inject, onUpdated, ref } from "vue";

export default {
  setup() {
    let tit = inject("tit"); //全局变量
    let sortAge = ref("default");
    let sData = [
      {
        id: 0,
        name: "Alice",
        contactNum: 12345678910,
        age: 18,
      },
      {
        id: 2,
        name: "Any",
        contactNum: 12345678910,
        age: 20,
      },
      {
        id: 1,
        name: "Tom",
        contactNum: 22345678910,
        age: 19,
      },
    ];
    let aa = ref([...sData]);
    let stuData = computed(() => {
      let data = [...aa.value];
      // 排序data
      if (sortAge.value !== "default") {
        data.sort((a, b) =>
          sortAge.value === "asc" ? a.age - b.age : b.age - a.age
        );
      }
      return data;
    });
    onUpdated(() => {
      sData.sort((a, b) => a.age - b.age);
    });
    // 删除
    function del(id) {
      aa.value = sData.filter((item) => item.id !== id);
    }
    return { stuData, tit, sortAge, del };
  },
};
</script>